package day7;

import java.util.ArrayList;

public class ch2 {

    public int orangesRotting(int[][] grid) {

        ArrayList<int[]> array = new ArrayList<>();

        int m = grid.length;
        int n = grid[0].length;
        //boolean[][] bool = new boolean[m][n];
        int[][] arr = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};

        int sum = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j]==2){
                    array.add(new int[]{i,j});
                    //bool[i][j] = true;
                }
            }
        }

        while(!array.isEmpty()){
            int num = array.size();
            boolean flag = false;
            for (int k = 0; k < num; k++) {
                int[] tep = array.remove(0);
                for (int q = 0; q <4; q++) {
                    int i = tep[0]+arr[q][0];
                    int j = tep[1]+arr[q][1];
                    if(i<0||i>=m) continue;
                    if(j<0||j>=n) continue;
                    if(grid[i][j]==1){
                        flag = true;
                        array.add(new int[]{i,j});
                        grid[i][j]=2;
                    }
                }
            }
            if(flag)  sum += 1;
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j]==1){
                    return -1;
                }
            }
        }

        return sum;



    }



}
